/*
  The MIT License
  
  Copyright (c) 2009 smath project
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/
package pl.smath.expression.model;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 * Abstract base class for all terms with multiple subterms
 * 
 * @author Krzysztof Langner
 *
 */
public abstract class AbstractMultiTerm extends Term{

	private final Vector<Term>	terms = new Vector<Term>();

	/**
	 * Constructor
	 * @param text
	 */
	protected AbstractMultiTerm(String text) {
		super(text);
	}

	/**
	 * Dodanie podwyrazenia
	 * @param c
	 */
	public void addTerm(Term term){
		
		terms.add(term);
	}
	
	/**
	 * Dodanie podwyrazen
	 * @param c
	 */
	public void addTerms(List<Term> c){
		
		terms.addAll(c);
	}
	
	/**
	 * @return tekst wyrażenia
	 */
	public Term copy(){
		AbstractMultiTerm term = createObject();;
		
		for(int i = 0; i < getTerms().size(); i++){
			term.addTerm(getTerms().get(i).copy());
		}
		
		term.setNegative(isNegative());
		return term;
	}

	/**
	 * Pobranie listy podwyrazen w postaci kopii tablicy.
	 * Same wyrazenia nie sa kopiowane ale tablica tak
	 * @return
	 */
	public List<Term> getTerms(){
		Vector<Term>	copy = new Vector<Term>();
		Iterator<Term>	it = terms.iterator();
		
		while(it.hasNext()){
			copy.add(it.next());
		}
		
		return copy;
	}
	
	/**
	 * Ten term jest liczba
	 */
	@Override
	public boolean isNumber() {
		
		for(Term term: terms){
			if(!term.isNumber())
				return false;
		}
		
		return true;
	}
	
	
	/**
	 * Sprawdzenie czy 2 wyrazenia sa sobie równowazne.
	 * Czyli czy mozna postawic miedzy nimi znak = (w sensie matematycznym)
	 * Np. ponizesze wyrazenia sa rownowazne
	 * c*(a+b) i (b+a)*c
	 */
	@Override
	public boolean isAbsTheSame(Term term){
		Vector<Term>	tempList = new Vector<Term>();
		
		if(!(term instanceof AbstractMultiTerm))
			return false;

		List<Term>	compareTerms = ((AbstractMultiTerm)term).getTerms();
		if(terms.size() != compareTerms.size())
			return false;
		
		// skopiowanie do tablicy tymczasowej podwyrazeń, tak by te znalezione mozna było usuwać
		tempList.addAll(terms);
		
		for(int i = 0; i < compareTerms.size(); i++){
			Term srcTerm = compareTerms.get(i);
			
			boolean found = false;
			for(int j = 0; j < tempList.size(); j++){
				if(srcTerm.isAbsTheSame(tempList.get(j)) && 
						srcTerm.isNegative() == tempList.get(j).isNegative())
				{
					tempList.remove(j);
					found = true;
					break;
				}
			}
			
			// Nie został znaleziony podobny element. Nie ma sensu porównywac dalej
			if(!found)
				break;
		}
		
		return tempList.isEmpty();
	}
	
	/**
	 * Usunięcie wewnetrznych nawiasów
	 * @return nowe wyrazenie lub to samo, jezeli nie ma wewnetrznych nawiasow
	 */
	public Term removeInnerBrackets(){
		return this;
	}
	
	/**
	 * Zamiana do stringa
	 */
	public String toString(){

		String output = "";

		for(Term term : getTerms()){
			
			if(output.length() > 0){
				output += getText();
			}

			output += term.toString();
		}
		
		if(isNegative())
			output = "-" + output;
		
		return output;
	}


	/**
	 * Transformacja wezla sum
	 */
	@Override
	public Term transform(ITransform t) {
		Term outputTerm = null;
	
		outputTerm = t.process(this);
	
	    if(outputTerm == this){
	
	    	Vector<Term> newTerms = new Vector<Term>();
	    	boolean		modified = false;
	    	
	    	for(Term term : getTerms()){
	    		Term newTerm = term.transform(t);
	    		
	    		if(newTerm != null && !isZero(newTerm)){
	    			newTerms.add(newTerm);
	    		}
	    		
	    		if(newTerm != term){
	    			modified = true;
	    		}
	    	}
	    	
	    	if(modified){
	    		if(newTerms.size() > 0){
					outputTerm = createObject();
	        		outputTerm.setNegative(isNegative());
	        		((AbstractMultiTerm)outputTerm).addTerms(newTerms);
	        		outputTerm = ((AbstractMultiTerm)outputTerm).removeInnerBrackets();
	    		}
	    		else{
	    			outputTerm = new NumberTerm(0);
	    		}
	    	}
	    }
	    
	    if(outputTerm != this && outputTerm != null){
	    	outputTerm = outputTerm.transform(t);
	    }
	    
	    return outputTerm;
	}

	/**
	 * sortuje wyrazenia
	 */
	protected void sortTerms(Comparator<Term> comparator) {
		Collections.sort(terms, comparator);
	}

	
	/**
	 * funkcja sprawdza czy podane wyrazenie jest 0
	 * @param term
	 * @return
	 */
	protected boolean isZero(Term term){
		
		if(term instanceof NumberTerm){
			return ((NumberTerm)term).getValue() == 0;
		}
		
		return false;
	}


	/**
	 * Ta funkcja jest potrzebne poniewaz GWT nie wspiera reflection.
	 * Zamiast niej mozna by uzyc
	 * getClass().newInstance();
	 */
	protected abstract AbstractMultiTerm createObject();

	
}
